package cn.com.lushunming.oauthclient.controller;


import com.google.common.collect.ImmutableMap;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Collections;
import java.util.Map;

@Controller
@RequestMapping("callback")
public class CallBackController {
    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("")
    public String callback(HttpServletRequest request, Model model) {

        //Http Basic 验证
        String clientAndSecret = "client:123";
        //这里需要注意为 Basic 而非 Bearer
        clientAndSecret = "Basic " + Base64.getEncoder().encodeToString(clientAndSecret.getBytes());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", clientAndSecret);
        //授权请求信息
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.put("code", Collections.singletonList(request.getParameter("code")));
        map.put("grant_type", Collections.singletonList("authorization_code"));
        map.put("redirect_uri", Collections.singletonList("http://localhost:9001/callback"));
        //HttpEntity
        HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
        //获取 Token
        ResponseEntity<Map> body = restTemplate.exchange("http://localhost:8080/oauth/token",
                HttpMethod.POST, httpEntity, Map.class);
        String accessToken = (String) body.getBody().get("access_token");
        String refreshToken = (String) body.getBody().get("refresh_token");

        model.addAllAttributes(body.getBody());

        return "callback/index";
    }
}
